package com.ftg.learn.framework.spring.chapter04.container;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * 准备工作
 *
 *  Class  类|接口|注解|枚举
 *  Field  字段|属性
 *  Method  方法
 *
 * @author 布衣
 */
public class FirstSpring {


    public static void main(String[] args) {
        //反射
        String classPath = "com.ftg.learn.framework.mybatis.chapter04.Dog";

        try {
            //关联对象  aClass
            Class<Dog> aClass = (Class<Dog>) Class.forName(classPath);
            //第二个反射方式
            Class c1 = String.class;

            //关联对象实例化  1.8以前
            Dog dog = aClass.newInstance();


//            //jdk1.8以后
//            Constructor<Dog> constructor = aClass.getConstructor();
//            Dog dog1 = constructor.newInstance();
            //机制获取类里面的属性
            Field fs = aClass.getDeclaredField("name");
            System.out.println("属性名称："+fs.getName());
            System.out.println("属性类型："+fs.getType().getName());
            //设置允许访问
            fs.setAccessible(true);
            fs.set(dog,"小墨");

            //遍历
            Field[] declaredFields = aClass.getDeclaredFields();
            for (int i = 0; i < declaredFields.length; i++) {
                System.out.println(declaredFields[i].getName());
            }

            //方法
            Method writeMethod = aClass.getMethod("setName",String.class);
            writeMethod.invoke(dog,"小红 ");

            Method method = aClass.getMethod("getName");
            System.out.println("返回值类型:"+method.getReturnType());
            System.out.println("参数类型:"+ Arrays.toString(method.getParameterTypes()));
//            invoke 执行
            System.out.println(method.invoke(dog));

        } catch (ClassNotFoundException | NoSuchFieldException | InstantiationException | IllegalAccessException |
                 NoSuchMethodException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

}
